package top.cardone.validator.func;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author yao hai tao
 * @date 2016/9/19
 */
@Log4j2
public class RegularValidatorFunc extends RequiredValidatorFunc {

    public RegularValidatorFunc() {
        this.code = "regular";
    }

    @Override
    public Map<String, Object> func(Map<String, Object> map, String key, Object rule, Object message) {
        log.debug(this.code + ":" + key);

        String val = MapUtils.getString(map, key);

        if (StringUtils.isBlank(val)) {
            return null;
        }

        if (rule == null) {
            return null;
        }

        if (Pattern.compile(String.valueOf(rule)).matcher(val).matches()) {
            return null;
        }

        return this.getMessage(key, message, new Object[0]);
    }
}
